# -*- coding: utf-8 -*-
'''
Create on 20200421
@author:menglei
'''
import urllib
from urllib import parse
from urllib import request
import time
import hashlib
import json
import pdd
import base64

P_CLIENT_ID='client_id'
P_CLIENT_SECRET='client_secret'
P_DATA_TYPE='data_type'
P_TIMESTAMP='timestamp'
P_API='type'
P_SIGN = "sign"
P_SESSION='access_token'
P_CODE = 'error_code'
P_SUB_CODE = 'sub_code'
P_MSG = 'error_msg'
P_SUB_MSG = 'sub_msg'
P_REQUEST_ID='request_id'
N_REST = '/api/router'

def sign(secret, parameters):

    # ===========================================================================
    # '''签名方法
    # @param secret: 签名需要的密钥
    # @param parameters: 支持字典和string两种
    # '''
    # ===========================================================================
    # 如果parameters 是字典类的话

#    del parameters['client_secret']
    if hasattr(parameters, "items"):
        parameters = "%s%s%s" % (secret,
                                 str().join('%s%s' % (key, parameters[key]) for key in sorted(parameters)),
                                 secret)
    m = hashlib.md5()
    m.update(parameters.encode('utf8'))
    sign = m.hexdigest().upper()

    return sign

class PddException(Exception):
    # ===========================================================================
    # 业务异常类
    # ===========================================================================
    def __init__(self):
        self.errorcode = None
        self.message = None
        self.subcode = None
        self.submsg = None
        self.requestid = None


    def __str__(self, *args, **kwargs):
        sb = "errorcode=" + str(self.errorcode) + \
             " message=" + str(self.message) + \
             " subcode=" + str(self.subcode) + \
             " submsg=" + str(self.submsg) + \
             " requestid=" + str(self.requestid)

        return sb




class RequestException(Exception):
    # ===========================================================================
    # 请求连接异常类
    # ===========================================================================
    pass

class RestApi():
    def __init__(self,domain='https://gw-api.pinduoduo.com'):
        self.__domain = domain
        self.__httpmethod = "POST"
        if (pdd.getDefaultAppInfo()):
            self.__client_id = pdd.getDefaultAppInfo().client_id
            self.__client_secret = pdd.getDefaultAppInfo().client_secret

    def timeStrToTimeStamp(timestr):
        return int(time.mktime(time.strptime(timestr, "%Y-%m-%d %H:%M:%S")))

    def get_request_header(self):
        return {
            'Content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
            "Cache-Control": "no-cache",
            "Connection": "Keep-Alive",
        }

    def set_app_info(self, appinfo):
        # =======================================================================
        # 设置请求的app信息
        # @param appinfo: import top
        #                 appinfo top.appinfo(appkey,secret)
        # =======================================================================
        self.__client_id = appinfo.client_id
        self.__client_secret = appinfo.client_secret
    def getapiname(self):
        return ""

    def getMultipartParas(self):
        return [];

    def getTranslateParas(self):
        return {"client_sectet",};

    def _check_requst(self):
        pass

    def getResponse(self,authrize=None,timeout=30):
        sys_parameters={
            P_CLIENT_ID:self.__client_id,
            P_TIMESTAMP: str(int(time.time())),
            P_DATA_TYPE:'JSON',
            P_API: self.getapiname(),
        }

        if authrize is not None:
            sys_parameters[P_SESSION] = authrize
        application_parameter = self.getApplicationParameters()
        sign_parameter = sys_parameters.copy()
        sign_parameter.update(application_parameter)
        sys_parameters.update(application_parameter)
        sys_parameters[P_SIGN] = sign(self.__client_secret, sign_parameter)
        header = self.get_request_header();
        url = self.__domain + N_REST + "?" + parse.urlencode(sys_parameters)
        request=urllib.request.Request(url,header)
        data=urllib.parse.urlencode(application_parameter).encode('utf8')

        response=urllib.request.urlopen(request,data={},timeout=timeout)
        if response.code is not 200:
            raise RequestException('invalid http status ' + str(response.status) + ',detail body:' + response.read())
        result = response.read()
        jsonobj = json.loads(result)

        if jsonobj.get("error_response"):
            error = PddException()
            if jsonobj["error_response"].get(P_CODE):
                error.errorcode = jsonobj["error_response"][P_CODE]
            if jsonobj["error_response"].get(P_MSG):
                error.message = jsonobj["error_response"][P_MSG]
            if jsonobj["error_response"].get(P_SUB_CODE):
                error.subcode = jsonobj["error_response"][P_SUB_CODE]
            if jsonobj["error_response"].get(P_SUB_MSG):
                error.submsg = jsonobj["error_response"][P_SUB_MSG]
            error.requestid = jsonobj["error_response"][P_REQUEST_ID]
            raise error
        return jsonobj


    def getApplicationParameters(self):
        application_parameter = {}
        for key, value in self.__dict__.items():
            if not key.startswith("__") and not key in self.getMultipartParas() and not key.startswith(
                    "_RestApi__") and value is not None:
                if (key.startswith("_")):
                    application_parameter[key[1:]] = value
                else:
                    application_parameter[key] = value
        # 查询翻译字典来规避一些关键字属性
        translate_parameter = self.getTranslateParas()
        for key, value in application_parameter.items():
            if key in translate_parameter:
                application_parameter[translate_parameter[key]] = application_parameter[key]
                del application_parameter[key]
        return application_parameter